package com.study.guide.codec.protobuf;


import com.study.guide.codec.protobuf.proto.SubscribeReqProto;
import com.study.guide.codec.protobuf.proto.SubscribeRespProto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class TimeServerHandler extends SimpleChannelInboundHandler<Object> {


	@Override
	public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		SubscribeReqProto.SubscribeReq req = (SubscribeReqProto.SubscribeReq)msg;
		if("Lilinfeng".equalsIgnoreCase(req.getUserName())){
			System.out.println("Server accept client subscribe req : [ "+req.toString()+" ]");
			ctx.writeAndFlush(resp(req.getSubReqId()));
		}
	}
	private SubscribeRespProto.SubscribeResp resp(int subReqId){
		SubscribeRespProto.SubscribeResp.Builder builder =
				SubscribeRespProto.SubscribeResp.newBuilder();
		builder.setSubReqId(subReqId)
				.setRespCode(0)
				.setDesc("Netty book order succeed,3 days later,sent to the designated address");
		return builder.build();
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("------------服务端激活");
	}
}
